<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>{{ title }}</h3>
      <el-form ref="dataForm" :rules="rules" :model="dataForm" label-width="150px">
        <el-form-item v-if="dataForm.id" v-show="false" label="id" prop="id">
          <el-input v-model="dataForm.id"/>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="dataForm.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="类型" prop="articleClassId">
          <el-select
            v-model="dataForm.articleClassId"
            style="width: 20%">
            <el-option v-for="(item,index) in articleClassList" :key="index" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图片" prop="imgUrl">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeFileUplod"
            class="avatar-uploader"
            accept=".jpg, .jpeg, .png, .gif"
          >
            <img v-if="dataForm.imgUrl" ref="adImg" :src="dataForm.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <editor :init="editorInit" v-model="dataForm.content" style="min-height: 200px;"/>
        </el-form-item>
      </el-form>
      <div class="op-container">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="!dataForm.id" type="primary" @click="handleUpsert">保存文章</el-button>
        <el-button v-if="dataForm.id" type="primary" @click="handleUpsert">更新文章</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  createArticle,
  updateArticle,
  detailArticle
} from '@/api/article'
import { uploadPath, beforeFileUplod } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Editor from '@tinymce/tinymce-vue'
import { createStorage } from '@/api/storage'
import { articleClassSelect } from '@/api/articleClass'

export default {
  name: 'ArticleAddForm',
  components: { Editor },
  props: {},
  data() {
    return {
      uploadPath,
      beforeFileUplod,
      title: '添加',
      dataForm: {
        id: undefined,
        title: undefined,
        articleClassId: undefined,
        imgUrl: undefined,
        content: undefined
      },
      articleClassList: [],
      rules: {
        id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        articleClassId: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
        imgUrl: [
          { required: true, message: '图片不能为空', trigger: 'blur' }
        ]
      },
      editorInit: {

        language: 'zh_CN',
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        ADMINTOKEN: getToken()
      }
    }
  },
  created() {
    articleClassSelect().then(response => {
      this.articleClassList = response.data.data
      console.log(this.articleClassList, 123)
    })
    const articleId = this.$route.query.id
    if (articleId) {
      detailArticle(articleId).then(response => {
        this.title = '编辑'
        this.dataForm = Object.assign({}, response.data.data)
      })
    }
  },
  methods: {
    handleCancel() {
      this.$router.push({ path: '/article/article' })
    },
    handleUpsert() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          // 没有id就是添加，有id就是修改
          if (this.dataForm.id) {
            updateArticle(this.dataForm)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '更新文章成功'
                })
                this.$router.push({ path: '/article/article' })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          } else {
            createArticle(this.dataForm)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加文章成功'
                })
                this.$router.push({ path: '/article/article' })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        } else {
          this.$notify.error({
            title: '失败',
            message: '请完善以上表单'
          })
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.dataForm.imgUrl = res.url
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
